import { asyncRoutes, constantRoutes } from '/@/router/index'
import Layout from '/@/layout/index.vue'
import { constantRouterComponents } from '/@/router/generator-routers.js'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
	if (route.meta && route.meta.roles) {
		return roles.some((role) => route.meta.roles.includes(role))
	} else {
		return true
	}
}
function generateOptions(params) {//生成Cascader级联数据
 
	var result = [];
	for (let param of params) {
		if (param.pid == 0) {//判断是否为顶层节点
			var parent = {//转换成el-Cascader可以识别的数据结构
				'name': param.url.substring(1),
				'path': param.url,
				"component": Layout,
				"meta": {
					title: param.name,
					icon: param.icon, 
				},
			}
			parent.children = getchilds(param.id, params);//获取子节点
			result.push(parent);
		}
	}
	return result;
};
function getPath(n) {
	var name = n.substring(1);
	// var url = name.lastIndexOf("/");
	return name;
}
function getchilds(id, array) {
	let childs = new Array();
	for (let arr of array) {//循环获取子节点
		if (arr.pid == id) {
			childs.push({
				'name': arr.url.substring(1),
				'path': "/manage" + arr.url,
				"component":  constantRouterComponents[getPath(arr.url)],
				"meta": {
					title: arr.name,
					icon: arr.icon
				}
			});

			
		}
	}
	for (let child of childs) {//获取子节点的子节点
		let childscopy =getchilds(child.value, array);//递归获取子节点
 
		if (childscopy.length > 0) {
			child.children = childscopy;
		}
	}
	return childs;
};
/**
 * 遍历后台传来的路由字符串，转换为组件对象
 * @param {*} routerMap 
 */
function filterRouter(routerMap) {
	const accessedRouters = routerMap.filter(route => {
		route.component = (resolve) => require(['@/pages' + route.path + ''], resolve)
		if (route.children && route.children.length) {
			route.children = filterRouter(route.children)
		}
		return true
	})
	return accessedRouters
}
 
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
	const res = []

	routes.forEach((route) => {
		const tmp = { ...route }
		if (hasPermission(roles, tmp)) {
			if (tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, roles)
			}
			res.push(tmp)
		}
	})

	return res
}

const state = {
	routes: [],
	addRoutes: []
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes
		state.routes = constantRoutes.concat(routes)
	}
}

const actions = {
	generateRoutes({ commit }, roles) {
		 

		return new Promise((resolve) => {
			let accessedRoutes
			accessedRoutes = [...asyncRoutes, ...generateOptions(roles)]
			// if (roles.includes('admin')) {
			// 	accessedRoutes = asyncRoutes || []
			// } else {
			// 	accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
			// }
		 
			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
